package study.reactive.springboot.webflux.support.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;

import java.util.Objects;

@Slf4j
public abstract class WebUtils {

    public static final String X_REQUEST_ID = "X-Request-Id";

    private WebUtils() {
    }

    /**
     * 获取 ServerHttpRequest
     */
    public static ServerHttpRequest getHttpRequest(ServerWebExchange exchange) {
        return exchange.getRequest();
    }

    /**
     * 获取 ServerHttpResponse
     */
    public static ServerHttpResponse getHttpResponse(ServerWebExchange exchange) {
        return exchange.getResponse();
    }

    /**
     * 获取请求头
     */
    public static String getRequestHeader(ServerWebExchange exchange, String name) {
        return getHeader(getHttpRequest(exchange), name);
    }

    public static String getHeader(ServerHttpRequest request, String name) {
        HttpHeaders headers = request.getHeaders();
        String value = null;
        if (Objects.nonNull(headers)) {
            value = headers.getFirst(name);
        }
        return value;
    }

    /**
     * 获取响应头
     */
    public static String getResponseHeader(ServerWebExchange exchange, String name) {
        return getHeader(getHttpResponse(exchange), name);
    }

    public static String getHeader(ServerHttpResponse response, String name) {
        HttpHeaders headers = response.getHeaders();
        String value = null;
        if (Objects.nonNull(headers)) {
            value = headers.getFirst(name);
        }
        return value;
    }

    /**
     * 获取Cookie值
     */
    public static String getCookieValue(ServerWebExchange exchange, String name) {
        ServerHttpRequest request = getHttpRequest(exchange);
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        String value = null;
        if (Objects.nonNull(cookies)) {
            HttpCookie cookie = cookies.getFirst(name);
            if (Objects.nonNull(cookie)) {
                value = cookie.getValue();
            }
        }
        return value;
    }

    /**
     * 获取Request Id值
     */
    public static String getRequestId(ServerWebExchange exchange) {
        return getRequestHeader(exchange, X_REQUEST_ID);
    }
}
